﻿using FastData.Caching;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Linq.Mapping;
using System.Reflection;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;

namespace FastData
{
    public class InsertQuery : QueryBase
    {
        public InsertQuery(DataAccess data)
            : base(data)
        {
        }

        internal override string GetCommandText(ExecuteType type)
        {
            return Data.Provider.CreateInsertText(this, type);
        }

        public InsertQuery Field(string name, object value)
        {
            return Field(name, value, true);
        }

        public InsertQuery Field(string name, object value, bool antiXSS)
        {
            AddField(name, value, antiXSS);
            return this;
        }

        public void ExecuteLazy()
        {
            Data.ExecuteLazy(this);
        }

        public void Execute()
        {
            Data.ExecuteNonQuery(this);
        }

        public async Task<int> ExecuteAsync()
        {
            return await Data.ExecuteNonQueryAsync(this);
        }

        public object ExecuteId()
        {
            if (Data.Provider.SupportInsertedId)
            {
                return Data.ExecuteScalar(this);
            }
            else
            {
                Data.ExecuteNonQuery(this);
                return Data.GetLastIdentity();
            }
        }

        public object ExecuteId(string idName)
        {
            IdName = idName;
            return ExecuteId();
        }

        internal override void ExecuteCompleted()
        {
            base.ExecuteCompleted();
            CacheProvider.Remove(new TableDependency(TableName));
        }
    }

}
